
angular.module('U9ImHd.services')

.factory('HttpInterceptor', ['$rootScope', '$q', '$cordovaNetwork', 'Auth', function($rootScope, $q, $cordovaNetwork, Auth) {
    return {
        request: function(config) {
            if (navigator.connection && config.needOnLine) {
                if ($cordovaNetwork.isOnline()) {
                    config.headers = config.headers || {};
                    config.headers.Authorization = 'Bearer ' + Auth.getToken();
                    return config;
                } else {
                    if (!config.ignoreErrorHandler) {
                        $rootScope.$broadcast('responseError', {
                            message: '设备未连接网络'
                        });
                    }
                    return $q.reject(config);
                }
            } else {
                config.headers = config.headers || {};
                config.headers.Authorization = 'Bearer ' + Auth.getToken();
                return config;
            }
        },
        response: function (response) {
            if (response !== null && 
                response.status === 200 && 
                !response.config.ignoreErrorHandler &&
                (response.config.url.indexOf('/api') !== -1 || response.config.url.indexOf('/open') !== -1)
            ) {
                var data = response.data;
                if (data.Error || (data.status && data.status !== '0000')) {
                    $rootScope.$broadcast('responseError', data.Error || {
                        message: data.desc
                    });
                }
            }
            return response || $q.when(response);
        },
        responseError: function(rejection) {
            if (!rejection.config.ignoreErrorHandler && rejection !== null && rejection.status === -1) {
                $rootScope.$broadcast('responseError', {
                    message: '连接超时，请稍后重试'
                });
            }
            return $q.reject(rejection);
        }
    };
}]);
